import { app, ipcMain } from 'electron'
import AutoLaunch from 'auto-launch'

// 创建 AutoLaunch 实例
const autoLauncher = new AutoLaunch({
  name: app.getName(), // 自动应用名称
  path: app.getPath('exe'), // 获取 Electron 应用的可执行文件路径
  isHidden: true // 是否在启动时隐藏应用窗口
})

/**
 * 检查是否已经设置了开机自启
 * @returns {Promise<boolean>} 是否已启用开机自启
 */
const isAutoLaunchEnabled = (): Promise<boolean> => autoLauncher.isEnabled()

/**
 * 设置开机自启
 * @returns {Promise<boolean>} 操作是否成功
 */
const setAutoLaunch = async (): Promise<boolean> => {
  try {
    const isEnabled = await isAutoLaunchEnabled()
    if (!isEnabled) {
      await autoLauncher.enable()
    }
    console.log('Auto launch enabled')

    return true
  } catch (err) {
    console.error('Error setting auto launch:', err)
    throw err
  }
}

/**
 * 关闭开机自启
 * @returns {Promise<boolean>} 操作是否成功
 */
const unsetAutoLaunch = async (): Promise<boolean> => {
  try {
    const isEnabled = await isAutoLaunchEnabled()
    if (isEnabled) {
      await autoLauncher.disable()
    }
    console.log('Auto launch disabled')
    return true
  } catch (err) {
    console.error('Error unsetting auto launch:', err)
    throw err
  }
}

// 监听主进程与渲染进程的 IPC 通信
ipcMain.handle('isAutoLaunchEnabled', async () => {
  try {
    return await isAutoLaunchEnabled()
  } catch (err) {
    console.error('Error checking auto launch status:', err)
    throw err
  }
})

ipcMain.handle('setAutoLaunch', async () => {
  try {
    return await setAutoLaunch()
  } catch (err) {
    console.error('Error enabling auto launch:', err)
    throw err
  }
})

ipcMain.handle('unsetAutoLaunch', async () => {
  try {
    return await unsetAutoLaunch()
  } catch (err) {
    console.error('Error disabling auto launch:', err)
    throw err
  }
})

export { isAutoLaunchEnabled, setAutoLaunch, unsetAutoLaunch }
